package myQueue;

public class MyCircleSequeQueue<T> { //循环队列泛型类

    final int MaxSize = 100;        //假设容量为100
    private T[] data;            //存放队列中的元素
    private int front, rear;        //队头队尾指针

    public MyCircleSequeQueue()        //构造方法
    {
        data = (T[]) new Object[MaxSize];
        front = 0;
        rear = 0;
    }

    //队列的基本运算算法
    public boolean empty()    //判断队列是否为空
    {
        return front == rear;
    }

    public void push(T e)            //元素e进队
    {
        if ((rear + 1) % MaxSize == front)        //队满
            throw new IllegalArgumentException("队满");
        rear = (rear + 1) % MaxSize;
        data[rear] = e;
    }

    public T pop()                //出队元素
    {
        if (empty())            //队空
            throw new IllegalArgumentException("队空");
        front = (front + 1) % MaxSize;
        return (T) data[front];
    }

    public T peek()            //取队头元素
    {
        if (empty())            //队空
            throw new IllegalArgumentException("队空");
        return (T) data[(front + 1) % MaxSize];
    }

    public int size()        //返回队中元素个数
    {
        return (rear - front + MaxSize) % MaxSize;
    }

    public static boolean pushk(MyCircleSequeQueue<Integer> qu,
                                int k, Integer e)
    //进队第k个元素e
    {
        Integer x;
        int i = 1, n = qu.size();
        if (k < 1 || k > n + 1) return false;    //参数k错误返回false
        if (k <= n) {
            for (i = 1; i <= n; i++)        //循环处理队中所有元素
            {
                if (i == k) qu.push(e);    //将e元素进队到第k个位置
                x = qu.pop();            //出队元素x
                qu.push(x);            //进队元素x
            }
        } else qu.push(e);            //k=n+1时直接进队e
        return true;
    }

    public static Integer popk(MyCircleSequeQueue<Integer> qu, int k)
    //出队第k个元素
    {
        Integer x, e = 0;
        int i = 1, n = qu.size();
        if (k < 1 || k > n)            //参数k错误
            throw new IllegalArgumentException("参数错误");
        for (i = 1; i <= n; i++)            //循环处理队中所有元素
        {
            x = qu.pop();            //出队元素x
            if (i != k) qu.push(x);        //将非第k个元素进队
            else e = x;            //取第k个出队的元素
        }
        return e;
    }


}
